/* in html. need jQuery
<img id="rndimg">
*/

var urlArray = ['yaimg'];

/*
// include jquery 
var script = document.createElement('script');
script.src = 'http://code.jquery.com/jquery-2.1.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
*/

//var url = 'yaimg';
var url = urlArray[(Math.floor(Math.random() * urlArray.length))] ;

var infoLink = "http://api.tumblr.com/v2/blog/" + url + ".tumblr.com/info?";
var photoLink = "http://api.tumblr.com/v2/blog/" + url + ".tumblr.com/posts?";

$.ajax({
    type: "GET",
    url : infoLink,
    dataType: "jsonp", 
    data: {
        // http://www.tumblr.com/oauth/apps :: FriiNoView OAuth consumer key:
        api_key: "Vw6ftsZVq4oUg9vK7ZGOKGThqGQ2xfsRr7cy0MyKYvEC4dot14",
    }
}).done(function( data ) {
    _totalNo = data.response.blog.posts;
    
    // 0 ~ (totalNo-1) random
    var rnd = 0 + Math.floor(Math.random() * _totalNo) ;
    
    $.ajax({
        type: "GET",
        url : photoLink,
        dataType: "jsonp", 
        data: {
            // http://www.tumblr.com/oauth/apps :: FriiNoView OAuth consumer key:
            api_key: "Vw6ftsZVq4oUg9vK7ZGOKGThqGQ2xfsRr7cy0MyKYvEC4dot14",
            limit:1,
            offset:rnd
            //offset:3892
        }
    }).done(function( data ) {
        $.each(data.response.posts, function(){
            var curUrl = this.post_url;
            
            var _photos = this.photos;
            $('#viewer').append("<p align=center style='margin-top:-3px'>" + _photos.length + "</p>");
            var imgIdx = 0;
            if (_photos.length > 1)
            {
                imgIdx = 0 + Math.floor(Math.random() * _photos.length) ;
            }
            $("#rndimg").attr('src', _photos[imgIdx].alt_sizes[1].url);
            
            // img click link
            $("#rndimg").click(function() {
                //window.location.href = curUrl; // open currnet window
                window.open(curUrl,'_blank'); // open new window
            });
        });
    });
});     